<?php
defined('_JEXEC') or die;

jimport('joomla.application.component.controller');
JTable::addIncludePath('components/com_sanpham/tables');

class SanphamController extends JController {
	
	protected $default_view = 'posts';
	
	function display($cachable = false)
	{
		// call parent behavior
		parent::display();
	}
	
	public function apply()
	{
		//var_dump(JRequest::get('post')); exit();
		global $app;		
		$view = JRequest::getVar('view');
	
		//v1. khởi tạo đối tượng bảng
		$tb = JTable::getInstance($view,'SanphamTable');
		
		//v2. lấy dữ liệu từ client post/get lên
		$tb->bind(JRequest::get('post'));
		
		// neu la insert new thi lay gio hien tai
		if (!$tb->id) {
			$tb->created = JFactory::getDate()->toMySQL();
		}
		
		if (!$tb->store()) {
			JError::raiseWarning('ko luu dc');
		}
		
		$app->redirect('index.php?option=com_sanpham&view='.$view,'Luu thanh cong');
		//$this->setRedirect('index.php?option=com_sanpham&view='.$view,'Luu thanh cong');
		//$this->redirect();
	}
	
	public function remove()
	{
		global $app;
		$view 	= JRequest::getVar('view');
		$ids 	= JRequest::getVar('cid',array(0));
		
		$model 	= $this->getModel('posts');
		$model->delData($ids);
		$app->redirect('index.php?option=com_sanpham&view='.$view,'xoa thanh cong');
	}
	
	public function publish()
	{
		$this->_changeState('published',1);
	}
	
	public function unpublish() 
	{
		$this->_changeState('published',0);
	}

	public function _changeState($field,$state)
	{
		global $app;
		$cid 	= JRequest::getVar('cid');
		$view	= JRequest::getVar('view');
		$model 	= $this->getModel('posts');
		$model->changeState('id',$field,$state,$cid);
		$app->redirect('index.php?option=com_sanpham&view='.$view);
	}
}